<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <title>异常(try语句) | haijd</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  
  <meta name="keywords" content="c#学习笔记" />
  
  
  
  
  <meta name="description" content="异常(try语句)">
<meta name="keywords" content="c#学习笔记">
<meta property="og:type" content="article">
<meta property="og:title" content="异常(try语句)">
<meta property="og:url" content="http://www.hais2.com/2015/05/19/Exceptions-try-statements/index.html">
<meta property="og:site_name" content="haijd">
<meta property="og:description" content="异常(try语句)">
<meta property="og:locale" content="default">
<meta property="og:image" content="http://www.hais2.com/image/cSharp/cSharp15.png">
<meta property="og:image" content="http://www.hais2.com/image/cSharp/cSharp16.png">
<meta property="og:image" content="http://www.hais2.com/image/cSharp/cSharp17.png">
<meta property="og:image" content="http://www.hais2.com/image/cSharp/cSharp18.png">
<meta property="og:image" content="http://www.hais2.com/image/cSharp/cSharp19.png">
<meta property="og:image" content="http://www.hais2.com/image/cSharp/cSharp20.png">
<meta property="og:image" content="http://www.hais2.com/image/cSharp/cSharp21.png">
<meta property="og:image" content="http://www.hais2.com/image/cSharp/cSharp22.png">
<meta property="og:image" content="http://www.hais2.com/image/cSharp/cSharp23.png">
<meta property="og:image" content="http://www.hais2.com/image/cSharp/cSharp24.png">
<meta property="og:image" content="http://www.hais2.com/image/cSharp/cSharp25.png">
<meta property="og:image" content="http://www.hais2.com/image/cSharp/cSharp26.png">
<meta property="og:image" content="http://www.hais2.com/image/cSharp/cSharp27.png">
<meta property="og:image" content="http://www.hais2.com/image/cSharp/cSharp28.png">
<meta property="og:image" content="http://www.hais2.com/image/cSharp/cSharp29.png">
<meta property="og:image" content="http://www.hais2.com/image/cSharp/cSharp30.png">
<meta property="og:updated_time" content="2017-08-02T15:22:33.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="异常(try语句)">
<meta name="twitter:description" content="异常(try语句)">
<meta name="twitter:image" content="http://www.hais2.com/image/cSharp/cSharp15.png">
  
    <link rel="alternate" href="/atom.xml" title="haijd" type="application/atom+xml">
  
  <link rel="icon" href="/css/images/favicon.ico">
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  <link href="https://fonts.googleapis.com/css?family=Open+Sans|Montserrat:700" rel="stylesheet" type="text/css">
  <link href="https://fonts.googleapis.com/css?family=Roboto:400,300,300italic,400italic" rel="stylesheet" type="text/css">
  <link href="//cdn.bootcss.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet">
  <style type="text/css">
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/9749f0/00000000000000000001008f/27/l?subset_id=2&fvd=n5) format("woff2");font-weight:500;font-style:normal;}
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/90cf9f/000000000000000000010091/27/l?subset_id=2&fvd=n7) format("woff2");font-weight:500;font-style:normal;}
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/8a5494/000000000000000000013365/27/l?subset_id=2&fvd=n4) format("woff2");font-weight:lighter;font-style:normal;}
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/d337d8/000000000000000000010095/27/l?subset_id=2&fvd=i4) format("woff2");font-weight:400;font-style:italic;}</style>
    
  <link rel="stylesheet" id="athemes-headings-fonts-css" href="//fonts.googleapis.com/css?family=Yanone+Kaffeesatz%3A200%2C300%2C400%2C700&amp;ver=4.6.1" type="text/css" media="all">
  <link rel="stylesheet" href="/css/style.css">

  <script src="/js/jquery-3.1.1.min.js"></script>

  <!-- Bootstrap core CSS -->
  <link rel="stylesheet" href="/css/bootstrap.css" >
  <link rel="stylesheet" href="/css/hiero.css" >
  <link rel="stylesheet" href="/css/glyphs.css" >
  
    <link rel="stylesheet" href="/css/vdonate.css" >
  

</head>

<script>
var themeMenus = {};

  themeMenus["/"] = "Home"; 

  themeMenus["/archives"] = "Archives"; 

  themeMenus["/categories"] = "Categories"; 

  themeMenus["/tags"] = "Tags"; 

  themeMenus["/about"] = "About"; 

</script>


  <body data-spy="scroll" data-target="#toc" data-offset="50">


  <header id="allheader" class="site-header" role="banner">
  <div class="clearfix container">
      <div class="site-branding">

          <h1 class="site-title">
            
              <a href="/" title="haijd" rel="home"> haijd </a>
            
          </h1>

          
            <div class="site-description">Stay Hungry,Stay Foolish</div>
          
            
          <nav id="main-navigation" class="main-navigation" role="navigation">
            <a class="nav-open">Menu</a>
            <a class="nav-close">Close</a>
            <div class="clearfix sf-menu">

              <ul id="main-nav" class="nmenu sf-js-enabled">
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/">Home</a> </li>
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/archives">Archives</a> </li>
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/categories">Categories</a> </li>
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/tags">Tags</a> </li>
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/about">About</a> </li>
                    
              </ul>
            </div>
          </nav>


      </div>
  </div>
</header>




  <div id="container">
    <div id="wrap">
            
      <div id="content" class="outer">
        
          <section id="main" style="float:none;"><article id="post-Exceptions-try-statements" style="width: 66%; float:left;" class="article article-type-post" itemscope itemprop="blogPost" >
  <div id="articleInner" class="clearfix post-1016 post type-post status-publish format-standard has-post-thumbnail hentry category-template-2 category-uncategorized tag-codex tag-edge-case tag-featured-image tag-image tag-template">
    
    
      <header class="article-header">
        
  
    <h1 class="thumb" class="article-title" itemprop="name">
      异常(try语句)
    </h1>
  

      </header>
    
    <div class="article-meta">
      
	Posted on <a href="/2015/05/19/Exceptions-try-statements/" class="article-date">
	  <time datetime="2015-05-19T09:29:08.000Z" itemprop="datePublished">May 19, 2015</time>
	</a>

      
	<span id="busuanzi_container_page_pv">
	  本文总阅读量<span id="busuanzi_value_page_pv"></span>次
	</span>

    </div>
    <div class="article-entry" itemprop="articleBody">
      
        <h3 id="什么是异常"><a href="#什么是异常" class="headerlink" title="什么是异常"></a>什么是异常</h3><p>　　<strong>异常</strong>是程序中的运行时错误，它违反了一个系统的约束或应用程序约束，或出现了在正常操作是位于聊的情形。</p>
<h3 id="try语句"><a href="#try语句" class="headerlink" title="try语句"></a>try语句</h3><p>　　<strong>try</strong>语句用来包裹住可能发生异常的代码块，如果异常发生的话，就提供代码处理该异常。<a id="more"></a><br><img src="/image/cSharp/cSharp15.png" alt=""></p>
<h3 id="异常类"><a href="#异常类" class="headerlink" title="异常类"></a>异常类</h3><p>　　有许多不同类型的异常可以在程序中发生。BCL定义了许多类，每一个类代表一个指定的异常类型，当一个异常发生时，CLR将：<br>　　■ 创建该类型的异常对象<br>　　■ 寻找适当的catch子句来处理它</p>
<p>　　所有的异常类从根本上都是派生自<strong>System.Exception</strong>类：<br><img src="/image/cSharp/cSharp16.png" alt=""><br>　　异常对象含有只读属性，带有导致该异常的信息：<br><img src="/image/cSharp/cSharp17.png" alt=""></p>
<h3 id="catch子句"><a href="#catch子句" class="headerlink" title="catch子句"></a>catch子句</h3><p>　　<strong>catch</strong>子句处理异常，它有三种形式，允许不同级别的处理。<br><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//一般catch子句</span></span><br><span class="line"><span class="comment">//在catch关键字后面没有参数列表</span></span><br><span class="line"><span class="comment">//匹配try块中引起的任何类型的异常</span></span><br><span class="line">catch</span><br><span class="line">&#123;</span><br><span class="line">    Statements</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//特定catch子句</span></span><br><span class="line"><span class="comment">//带有异常类的名称作为单一参数</span></span><br><span class="line"><span class="comment">//匹配任何该名称类型的异常</span></span><br><span class="line"><span class="function"><span class="title">catch</span><span class="params">(ExceptionType)</span></span></span><br><span class="line">&#123;</span><br><span class="line">    Statements</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//带对象的特定catch子句</span></span><br><span class="line"><span class="comment">//在异常类名称之后包括一个标识符</span></span><br><span class="line"><span class="comment">//该标识符在catch子句块中相当于一个本地变量，并被称为异常变量</span></span><br><span class="line"><span class="comment">//异常变量引用异常对象，并能被用于访问关于该变量的信息</span></span><br><span class="line"><span class="function"><span class="title">catch</span><span class="params">(ExceptionType InstID)</span></span></span><br><span class="line">&#123;</span><br><span class="line">    Statements</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　<strong>一般catch子句</strong>能够接受任何异常，但不能确定引发异常的类型。这只允许对任何可能发生的异常的普通处理和清理。<br>　　<strong>特定catch子句</strong>形式把一个异常类的名称作为参数。它匹配该指定类或派生自它的异常类的异常。<br>　　<strong>带对象的特定catch子句</strong>提供最多的关于异常的信息。它匹配该指定类的异常，或派生自它的异常类的异常。它还给出一个异常实例，称为<strong>异常变量</strong>，它是一个队CLR创建的异常对象的引用，可以在catch子句块内部访问异常变量的属性，以获取关于引起的异常的详细信息。</p>
<p>　　下面的代码处理IndexOutRangeException类型的异常，每当一个异常发生时，一个实际异常对象的引用被参数e传入代码。<br><figure class="highlight gradle"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//其中“IndexOutOfRangeException”是异常类型；“e”是异常变量；“e.Message”是访问异常变量</span></span><br><span class="line"><span class="keyword">catch</span>(IndexOutOfRangeException e)</span><br><span class="line">&#123;</span><br><span class="line">    Console.<span class="keyword">WriteLine</span>(<span class="string">"Message:&#123;0&#125;"</span>,e.Message);</span><br><span class="line">    Console.<span class="keyword">WriteLine</span>(<span class="string">"Source:&#123;0&#125;"</span>,e.<span class="keyword">Source</span>);</span><br><span class="line">    Console.<span class="keyword">WriteLine</span>(<span class="string">"Stack:&#123;0&#125;"</span>,e.StackTrace);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h3 id="使用catch子句的示例"><a href="#使用catch子句的示例" class="headerlink" title="使用catch子句的示例"></a>使用catch子句的示例</h3><p><strong>一般catch子句</strong>：<br><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Program</span></span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line">    <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">Main</span><span class="params">(<span class="built_in">string</span>[] args)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">try</span></span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">int</span> a = <span class="number">10</span>;</span><br><span class="line">            <span class="keyword">int</span> b = <span class="number">0</span>;</span><br><span class="line">            <span class="keyword">int</span> c = a / b;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">catch</span></span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">throw</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        Console.ReadKey();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>一般catch子句会处理try块中引起的任何异常。<br><img src="/image/cSharp/cSharp18.png" alt=""></p>
<p><strong>特定catch子句</strong>：<br><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Program</span></span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line">    <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">Main</span><span class="params">(<span class="built_in">string</span>[] args)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">try</span></span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">int</span> a = <span class="number">10</span>;</span><br><span class="line">            <span class="keyword">int</span> b = <span class="number">0</span>;</span><br><span class="line">            <span class="keyword">int</span> c = a / b;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">catch</span>(DivideByZeroException)</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">throw</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        Console.ReadKey();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>特定catch子句只会处理指定类型的异常信息。<br><img src="/image/cSharp/cSharp19.png" alt=""></p>
<p><strong>带对象的特定catch子句</strong><br><figure class="highlight arduino"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">class Program</span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">void</span> Main(<span class="keyword">string</span>[] args)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">try</span></span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">int</span> a = <span class="number">10</span>;</span><br><span class="line">            <span class="keyword">int</span> b = <span class="number">0</span>;</span><br><span class="line">            <span class="keyword">int</span> c = a / b;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="built_in">catch</span>(DivideByZeroException e)</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="built_in">Console</span>.WriteLine(<span class="string">"异常信息:&#123;0&#125;"</span>, e.Message);</span><br><span class="line">            <span class="built_in">Console</span>.WriteLine(<span class="string">"导致错误的应用程序或对象名称:&#123;0&#125;"</span>, e.Source);</span><br><span class="line">            <span class="built_in">Console</span>.WriteLine(<span class="string">"异常发生在:&#123;0&#125;"</span>, e.StackTrace);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="built_in">Console</span>.ReadKey();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>访问异常对象的属性<br><img src="/image/cSharp/cSharp20.png" alt=""></p>
<h3 id="catch子句段"><a href="#catch子句段" class="headerlink" title="catch子句段"></a>catch子句段</h3><p>　　catch子句段可以包含多个catch子句。<br><img src="/image/cSharp/cSharp21.png" alt=""><br>　　当异常发生时，系统按照顺序搜索catch子句的列表，第一个匹配该异常对象类型的catch子句被执行。因此，catch子句的排序有两个重要的规则：<br>　　■ 特定catch子句必须以一种顺序排列，最明确的异常类型第一，知道最普通的类型。例如，如果声明了一个派生自NullRefrenceException的异常类，那么为派生该异常类型的catch子句应该被列在NullRefrenceException的catch子句之前。<br>　　■ <strong>如果有一个一般catch子句，它必须是最后一个，并且在所有特定catch子句之后</strong>。使用一般catch子句是不好的，应该尽可能使用特定catch子句，一般catch子句通过让程序继续执行隐藏错误，让程序处于一种未知的状态。</p>
<h3 id="finally块"><a href="#finally块" class="headerlink" title="finally块"></a>finally块</h3><p>　　如果程序的控制流进入了一个带有finally块的try语句，那么finally块始终会被执行。<br><img src="/image/cSharp/cSharp22.png" alt=""><br>　　■　即使try块中有return语句，finally块也总是会在返回到调用代码之前执行。<br><figure class="highlight arduino"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">class Program</span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">void</span> Main(<span class="keyword">string</span>[] args)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">int</span> num = <span class="number">5</span>;</span><br><span class="line">        <span class="built_in">try</span></span><br><span class="line">        &#123;</span><br><span class="line">            <span class="built_in">if</span> (num&lt;<span class="number">10</span>)</span><br><span class="line">            &#123;</span><br><span class="line">                <span class="built_in">Console</span>.WriteLine(<span class="string">"带有return语句的try块"</span>);</span><br><span class="line">                <span class="built_in">return</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="built_in">else</span></span><br><span class="line">            &#123;</span><br><span class="line">                <span class="built_in">Console</span>.WriteLine(<span class="string">"不带return语句的try块"</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        finally</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="built_in">Console</span>.WriteLine(<span class="string">"这是finally块中的输出！！"</span>);</span><br><span class="line">            <span class="built_in">Console</span>.ReadKey();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="built_in">Console</span>.ReadKey();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　我们在这段代码中，我们首先让<code>num</code>的值小于10，这样就会执行<code>if</code>中的代码，我们就能看到带有<code>return</code>语句的try..finally语句是什么执行的。<br><img src="/image/cSharp/cSharp23.png" alt=""><br>　　从结果中可以看到，先执行了<code>if</code>中的<code>Console.WriteLine()</code>语句，然后执行了<code>finally</code>中的语句。<br>　　但是到底有没有执行return呢？稍微改动一下代码就知道了，将<code>finally</code>中的<code>Console.ReadKey()</code>语句删除掉，然后运行程序可以发现，控制台窗口一闪而过，但是我们的代码最后是写了<code>Console.ReadKey()</code>暂停语句的，这就可以想到，整个执行的过程了：程序首先判断<code>if</code>条件成立，然后执行了其中的代码，执行到<code>return</code>的时候，去检查有没有<code>finally</code>语句，发现有，然后执行了<code>finally</code>中的代码，最后返回来执行了<code>if</code>中<code>return</code>语句。 所以我们看到了最后一行暂停语句没有起作用，因为执行完<code>finally</code>中的代码后直接return出去了。</p>
<figure class="highlight arduino"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">class Program</span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">void</span> Main(<span class="keyword">string</span>[] args)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">int</span> num = <span class="number">20</span>;</span><br><span class="line">        <span class="built_in">try</span></span><br><span class="line">        &#123;</span><br><span class="line">            <span class="built_in">if</span> (num&lt;<span class="number">10</span>)</span><br><span class="line">            &#123;</span><br><span class="line">                <span class="built_in">Console</span>.WriteLine(<span class="string">"带有return语句的try块"</span>);</span><br><span class="line">                <span class="built_in">return</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="built_in">else</span></span><br><span class="line">            &#123;</span><br><span class="line">                <span class="built_in">Console</span>.WriteLine(<span class="string">"不带return语句的try块"</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        finally</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="built_in">Console</span>.WriteLine(<span class="string">"这是finally块中的输出！！"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="built_in">Console</span>.ReadKey();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>　　这次将<code>num</code>的赋值为20，让程序执行<code>else</code>中的代码，然后看看执行结果：<br><img src="/image/cSharp/cSharp24.png" alt=""></p>
<h3 id="为异常寻找处理代码"><a href="#为异常寻找处理代码" class="headerlink" title="为异常寻找处理代码"></a>为异常寻找处理代码</h3><p>　　当程序产生一个异常时，系统查看该程序是否为它提供了一个处理的代码。<br>　　■ 如果在try块内发生了异常，系统会查看是否有任何一个catch子句可能处理该异常。<br>　　■ 如果找到了适当的catch子句：<br>　　　　□ 该catch子句被执行<br>　　　　□ 如果有finally块，那么它也被执行</p>
<p>　　<strong>更进一步</strong><br>　　如果异常在一个没有被try语句保护的代码段中产生，或者try语句没有匹配的异常处理程序(catch)，系统将不得不更进一步寻找匹配的处理代码，为此他会按顺序搜索调用栈，看看是否存在带相匹配处理代码的try块。<br><img src="/image/cSharp/cSharp25.png" alt=""><br>　　在图的左边是代码的调用结构，在右边是调用栈。Method2被从Method1的try块内部调用，如果异常发生在Method2内的try块内部，系统会：<br>　　■ 首先，系统会查看Method2是否有能处理该异常的异常处理程序。<br>　　　　□ 如果有，Method2处理它，程序继续执行。<br>　　　　□ 如果没有，系统再延着调用栈找到Method1，寻找一个适当的处理代码。<br>　　■ 如果Method1有一个适当的catch子句，那么系统将：<br>　　　　□ 回到栈顶，那里是Method2。<br>　　　　□ 执行Method2的finally块，并把Method2弹出栈。<br>　　　　□ 执行Method1的catch子句和它的finally块。<br>　　■ 如果Method1没有适当的catch子句，系统会继续搜索调用栈。</p>
<p>　　<strong>处理异常的一般过程</strong><br><img src="/image/cSharp/cSharp26.png" alt=""></p>
<p>　　<strong>搜索调用栈的示例</strong><br><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title">Program</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">Main</span>(<span class="params"><span class="keyword">string</span>[] args</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        MyClass mc = <span class="keyword">new</span> MyClass();</span><br><span class="line">        <span class="keyword">try</span></span><br><span class="line">        &#123;</span><br><span class="line">            mc.A();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">catch</span> (DivideByZeroException e)</span><br><span class="line">        &#123;</span><br><span class="line">            Console.WriteLine(<span class="string">"Main方法中的catch子句~~"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">finally</span></span><br><span class="line">        &#123;</span><br><span class="line">            Console.WriteLine(<span class="string">"Main方法中的finally子句~~"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        Console.WriteLine(<span class="string">"Main方法中的异常处理~~"</span>);</span><br><span class="line">        Console.ReadKey();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title">MyClass</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">A</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">try</span></span><br><span class="line">        &#123;</span><br><span class="line">            B();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">catch</span> (NullReferenceException)</span><br><span class="line">        &#123;</span><br><span class="line">            Console.WriteLine(<span class="string">"A方法中的catch子句~~"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">finally</span></span><br><span class="line">        &#123;</span><br><span class="line">            Console.WriteLine(<span class="string">"A方法中的finally子句~~"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">B</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> x = <span class="number">10</span>, y = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">try</span></span><br><span class="line">        &#123;</span><br><span class="line">            x /= y;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">catch</span> (IndexOutOfRangeException)</span><br><span class="line">        &#123;</span><br><span class="line">            Console.WriteLine(<span class="string">"B方法中的catch子句~~"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">finally</span></span><br><span class="line">        &#123;</span><br><span class="line">            Console.WriteLine(<span class="string">"B方法中的finally子句~~"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>执行结果：<br><img src="/image/cSharp/cSharp27.png" alt=""><br>　　<strong>执行过程</strong>：<br>　　⒈ Main调用A，A调用B，B遇到一个<em>DivideByZeroException</em>异常。<br>　　⒉ 系统检查B的catch段寻找匹配的catch子句。虽然它有一个<em>IndexOutOfRangeException</em>的子句但是没有<em>DivideByZeroException</em>的。<br>　　⒊ 系统然后延着调用栈向下移动并检查A的catch段，在那里发现A也没有匹配的catch子句。<br>　　⒋ 系统继续延续调用栈向下，并检查Main方法的catch子句部分，在那里它发现Main方法确实有一个<em>DivideByZeroException</em>的子句。<br>　　⒌ 尽管匹配的catch子句现在被定位了，但并不立即执行。相反，系统回到栈的顶端，执行B的finally子句，并把B从调用栈中弹出。<br>　　⒍ 系统移动到A，执行它的finally子句，并把A从调用栈中弹出。<br>　　⒎ 最后，Main方法匹配的catch子句被执行，接着是它的finally子句，然后执行流程在Mian方法的try语句结尾之后继续。<br><img src="/image/cSharp/cSharp28.png" alt=""></p>
<h3 id="抛出异常"><a href="#抛出异常" class="headerlink" title="抛出异常"></a>抛出异常</h3><p>　　可以使用<code>throw</code>语句使代码显示的引发一个异常。语法如下：<br><code>throw ExceptionObject;</code></p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title">Program</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">Main</span>(<span class="params"><span class="keyword">string</span>[] args</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">string</span> str = <span class="literal">null</span>;</span><br><span class="line">        MyClass.ThrowMessage(str);</span><br><span class="line">        Console.ReadKey();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">class</span> <span class="title">MyClass</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">ThrowMessage</span>(<span class="params"><span class="keyword">string</span> arg</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">try</span></span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">if</span> (arg==<span class="literal">null</span>)</span><br><span class="line">            &#123;</span><br><span class="line">                ArgumentNullException ane = <span class="keyword">new</span> ArgumentNullException(<span class="string">"arg"</span>);</span><br><span class="line">                <span class="keyword">throw</span> ane;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">catch</span> (ArgumentNullException e)</span><br><span class="line">        &#123;</span><br><span class="line">            Console.WriteLine(<span class="string">"异常信息：&#123;0&#125;"</span>,e.Message);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>运行结果：<br><img src="/image/cSharp/cSharp29.png" alt=""><br>　　这段代码定义了一个名为<code>ThorwMessage</code>的方法，它带一个<code>string</code>类型的参数，在try块内部，它首先做检查以确认该参数是不是null，如果是null就创建一个<code>ArgumentNullExceptuion</code>实例并抛出(throw)它。这个异常的实例也被catch语句捕获，并且获得该异常实例的属性。</p>
<h3 id="不带异常对象的抛出"><a href="#不带异常对象的抛出" class="headerlink" title="不带异常对象的抛出"></a>不带异常对象的抛出</h3><p>　　<code>throw</code>语句还可以不带异常对象使用，在catch块内部：<br>　　■ 这种形式重新抛出当前异常，系统继续他的搜索，为该异常寻找另外的处理代码。<br>　　■ 这种形式只能用在catch语句的内部。</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title">Program</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">Main</span>(<span class="params"><span class="keyword">string</span>[] args</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">string</span> str = <span class="literal">null</span>;</span><br><span class="line">        MyClass.ThrowMessage(str);</span><br><span class="line">        Console.ReadKey();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">class</span> <span class="title">MyClass</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">ThrowMessage</span>(<span class="params"><span class="keyword">string</span> arg</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">try</span></span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">try</span></span><br><span class="line">            &#123;</span><br><span class="line">                <span class="keyword">if</span> (arg == <span class="literal">null</span>)</span><br><span class="line">                &#123;</span><br><span class="line">                    ArgumentNullException ane = <span class="keyword">new</span> ArgumentNullException(<span class="string">"arg"</span>);</span><br><span class="line">                    <span class="keyword">throw</span> ane;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">catch</span> (ArgumentNullException e)</span><br><span class="line">            &#123;</span><br><span class="line">                Console.WriteLine(<span class="string">"异常信息：&#123;0&#125;"</span>, e.Message);</span><br><span class="line">                <span class="keyword">throw</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">catch</span></span><br><span class="line">        &#123;</span><br><span class="line">            Console.WriteLine(<span class="string">"重新抛出了异常啦！！！！"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>运行结果：<br><img src="/image/cSharp/cSharp30.png" alt=""><br>　　从运行结果中可以看出，catch中的<code>throw</code>再一次抛出异常，造成了顶层<code>try...catch</code>语句中catch代码触发，其中的语句最后被打印了出来。</p>

      
    </div>
    <footer class="entry-meta entry-footer">
      
	<span class="ico-folder"></span>
    <a class="article-category-link" href="/categories/c/">c#</a>

      
  <span class="ico-tags"></span>
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/c-学习笔记/">c#学习笔记</a></li></ul>

      
        <div id="donation_div"></div>

<script src="/js/vdonate.js"></script>
<script>
var a = new Donate({
  title: '如果觉得我的文章对您有用，请随意打赏。您的支持将鼓励我继续创作!', // 可选参数，打赏标题
  btnText: 'Donate', // 可选参数，打赏按钮文字
  el: document.getElementById('donation_div'),
  wechatImage: '/css/images/wechatPay.png',
  alipayImage: '/css/images/alipay.jpg'
});
</script>
      

      
        
	<section id="comments" class="comment">
	  <div id="disqus_thread">
	  <noscript>Please enable JavaScript to view the <a href="//disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
	  </div>
	</section>

	<script type="text/javascript">
	var disqus_shortname = 'haijdblog';
	(function(){
	  var dsq = document.createElement('script');
	  dsq.type = 'text/javascript';
	  dsq.async = true;
	  dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
	  (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
	}());
	(function(){
	  var dsq = document.createElement('script');
	  dsq.type = 'text/javascript';
	  dsq.async = true;
	  dsq.src = '//' + disqus_shortname + '.disqus.com/count.js';
	  (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
	}());
	</script>


      
    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2015/05/20/c#-delegate/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          委托(delegate)
        
      </div>
    </a>
  
  
    <a href="/2015/05/13/C-#-types-storage-and-variable/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">c#类型、存储和变量</div>
    </a>
  
</nav>

  
</article>

<!-- Table of Contents -->

  <aside id="sidebar">
    <div id="toc" class="toc-article">
    <strong class="toc-title">Contents</strong>
    
      <ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#什么是异常"><span class="nav-number">1.</span> <span class="nav-text">什么是异常</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#try语句"><span class="nav-number">2.</span> <span class="nav-text">try语句</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#异常类"><span class="nav-number">3.</span> <span class="nav-text">异常类</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#catch子句"><span class="nav-number">4.</span> <span class="nav-text">catch子句</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用catch子句的示例"><span class="nav-number">5.</span> <span class="nav-text">使用catch子句的示例</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#catch子句段"><span class="nav-number">6.</span> <span class="nav-text">catch子句段</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#finally块"><span class="nav-number">7.</span> <span class="nav-text">finally块</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#为异常寻找处理代码"><span class="nav-number">8.</span> <span class="nav-text">为异常寻找处理代码</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#抛出异常"><span class="nav-number">9.</span> <span class="nav-text">抛出异常</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#不带异常对象的抛出"><span class="nav-number">10.</span> <span class="nav-text">不带异常对象的抛出</span></a></li></ol>
    
    </div>
  </aside>
</section>
        
      </div>
      <footer id="footer" class="site-footer">
  

  <div class="clearfix container">
      <div class="site-info">
	      &copy; 2018 haijd All Rights Reserved.
          
            <span id="busuanzi_container_site_uv">
              本站访客数<span id="busuanzi_value_site_uv"></span>人次  
              本站总访问量<span id="busuanzi_value_site_pv"></span>次
            </span>
          
      </div>
      <div class="site-credit">
        Theme by <a href="https://github.com/iTimeTraveler/hexo-theme-hiero" target="_blank">hiero</a>
      </div>
  </div>
</footer>


<!-- min height -->

<script>
    var contentdiv = document.getElementById("content");

    contentdiv.style.minHeight = document.body.offsetHeight - document.getElementById("allheader").offsetHeight - document.getElementById("footer").offsetHeight + "px";
</script>
    </div>
    <!-- <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
    <a href="/categories" class="mobile-nav-link">Categories</a>
  
    <a href="/tags" class="mobile-nav-link">Tags</a>
  
    <a href="/about" class="mobile-nav-link">About</a>
  
</nav> -->
    

<!-- mathjax config similar to math.stackexchange -->

<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    tex2jax: {
      inlineMath: [ ['$','$'], ["\\(","\\)"] ],
      processEscapes: true
    }
  });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
      tex2jax: {
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      }
    });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for(i=0; i < all.length; i += 1) {
            all[i].SourceElement().parentNode.className += ' has-jax';
        }
    });
</script>

<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>


  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css">
  <script src="/fancybox/jquery.fancybox.pack.js"></script>


<script src="/js/scripts.js"></script>
<script src="/js/bootstrap.js"></script>
<script src="/js/main.js"></script>








	<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js">
	</script>






  </div>

  <a id="rocket" href="#top" class=""></a>
  <script type="text/javascript" src="/js/totop.js" async=""></script>
</body>
</html>
